package com.zlll.winner.service.media;

import com.alibaba.fastjson.JSONObject;
import com.zlll.winner.business.model.media.MediaListenUserLog;
import com.zlll.winner.config.RabbitDelayConfig;
import com.zlll.winner.enums.CommonEnum;
import com.zlll.winner.mapper.media.MediaListenUserLogMapper;
import com.zlll.winner.business.service.media.IMediaListenUserLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlll.winner.service.media.async.MediaListenUserAsyncService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * <p>
 * 直播收听用户日志表 服务实现类
 * </p>
 *
 * @author Walert
 * @since 2019-10-16
 */
@Service
@Slf4j
public class MediaListenUserLogServiceImpl extends ServiceImpl<MediaListenUserLogMapper, MediaListenUserLog> implements IMediaListenUserLogService {

    @Autowired
    private MediaListenUserAsyncService listenUserAsyncService;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 直播用户收听记录方法
     * @param params
     * @return
     */
    @Override
    public Object saveListenInLog(JSONObject params){
        Long newListId = params.getLong("newListId");
        Long userId = params.getLong("userId");
        Integer type = params.getInteger("type");
        MediaListenUserLog mediaListenUserLog = new MediaListenUserLog();

        mediaListenUserLog.setNewListId(newListId);
        mediaListenUserLog.setUserId(userId);
        mediaListenUserLog.setIsDel(CommonEnum.DelEnum.UNDEL.val());
        mediaListenUserLog.setType(type);
        mediaListenUserLog.setCreateTime(System.currentTimeMillis());

        int insert = baseMapper.insert(mediaListenUserLog);
        if(insert > 0){
            listenUserAsyncService.saveMediaListenUser(mediaListenUserLog);
        }
        return mediaListenUserLog;
    }


    /**
     * MQ保存用户日志
     * @param params
     */
    @Override
    public void delaySaveLog(JSONObject params){
        log.info("直播延时记录用户日志====>{}",params.toJSONString());
        //第一个参数是前面RabbitMqConfig的交换机名称 第二个参数的路由名称 第三个参数是传递的参数 第四个参数是配置属性
        this.rabbitTemplate.convertAndSend(
                RabbitDelayConfig.LIVE_LISTEN_LOG_EXCHANGE,
                RabbitDelayConfig.LIVE_LISTEN_LOG_ROUTING_KEY,
                params,
                message -> {
                    // 指定延迟时间(单位是毫秒)
                    message.getMessageProperties().setDelay(1000);
                    return message;
                });
    }
}
